package uk.co.javahelp.sender.bulk.csv;

import java.io.IOException;
import java.io.Reader;

import uk.co.javahelp.sender.bulk.BulkSender;
import uk.co.javahelp.sender.message.Attachment;
import uk.co.javahelp.sender.message.Message;
import uk.co.javahelp.sender.message.MessageFactory;
import uk.co.javahelp.sender.message.MessageFactoryFactory;
import uk.co.javahelp.sender.message.Sender;
import au.com.bytecode.opencsv.CSVReader;

public class CsvBulkSender implements BulkSender {

	private static final String STATUS = "status";
	
	private final MessageFactoryFactory<String[]> factoryFactory;
	
    private final Sender sender;
		
	public CsvBulkSender(
            final MessageFactoryFactory<String[]> factoryFactory,
			final Sender sender) {
		this.factoryFactory = factoryFactory;
		this.sender = sender;
	}

	@Override
	public void sendInBulk(
			final String template,
			final Reader reader,
			final long throttle,
			final Attachment... attachments) throws IOException, InterruptedException {
		
		final CSVReader csvReader = new CSVReader(reader, ',', '"', 0);
	    String [] nextLine = csvReader.readNext();
	    if(nextLine != null) {
            final MessageFactory<String[]> factory = factoryFactory.createMessageFactory(template, nextLine, attachments);
    	    while ((nextLine = csvReader.readNext()) != null) {
				final Message message = factory.createMessage(nextLine);
		    	try {
					final String status = (String)message.getAttributes().get(STATUS);
					if("READY".equals(status)) {
					    System.out.println(String.format("Sending email to %s", message.getTo()));
						sender.send(message);
					} else {
					    System.out.println(String.format("Skipping email to %s", message.getTo()));
					}
				} catch (final Exception e) {
					System.err.println(message.toString() + " - " + e.getMessage());
				}
				Thread.sleep(throttle);
		    }
	    }
	}
}
